package top.syfy.oss.aliyun.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.syfy.oss.aliyun.response.ContentReturnType;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局统一异常处理
 *
 * @author awg
 * @date 2020/10/27 星期二
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理中定义业务异常
     *
     * @param e 业务异常
     * @return 异常信息的简要信息
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ContentReturnType bizExceptionHandler(HttpServletRequest request, BizException e) {
        logger.error("发生业务异常, 原因是: {}", e.getErrorMsg());
        return ContentReturnType.ofReturn(e.getErrorCode(), e.getErrorMsg(), null);
    }

    /**
     * 处理空指针异常
     *
     * @param e 空指针异常
     * @return 异常信息的简要信息
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ContentReturnType NPEExceptionHandler(HttpServletRequest request, NullPointerException e) {
        logger.error("发生空指针异常, 原因是: {}", e);
        return ContentReturnType.ofReturn(CommonEnum.BODY_NOT_MATCH, null);
    }

    /**
     * 处理其他异常
     *
     * @param e 业务异常
     * @return 异常信息的简要信息
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ContentReturnType exceptionHandler(HttpServletRequest request, Exception e) {
        logger.error("发生业务异常, 原因是: {}", e);
        return ContentReturnType.ofReturn(CommonEnum.INTERNAL_SERVER_ERROR, null);
    }

}
